package com.mrlv.ht.shiro;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import com.mrlv.ht.pojo.ModuLe;
import com.mrlv.ht.pojo.User;
import com.mrlv.ht.pojo.UserExample;
import com.mrlv.ht.pojo.UserExample.Criteria;
import com.mrlv.ht.service.IUserService;

public class AuthRealm extends AuthorizingRealm{

	@Resource
	private IUserService userService;
	
	@Override//权限管理的资料提交
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		//1.在前台页面添加shiro的标签。详情请看页面
		//2.根据subject的session，拿到当前已经登录用户的用户名，根据这个用户名来查询其权限
		//3.把这些权限的名字取出来，封装到集合里面
		//4.把shiro的权限管理员，叫出来，让它干活
		Subject subject = SecurityUtils.getSubject();
		String username = (String) subject.getSession().getAttribute("username");
		User user = userService.findModule(username);
		
		List<ModuLe> modules = user.getModules();
		
		List<String> list = new ArrayList<String>();
		
		for(ModuLe module : modules) {
			list.add(module.getName());
		}

		list.add("系统首页");
//		list.add("系统首页");
//		list.add("货运管理");
//		list.add("基础信息");
///		list.add("系统管理");
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addStringPermissions(list);
		return info;
	}

	@Override//登录验证的资料提交
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//1.根据token，拿出当前用户输入的用户名
		//2.根据用户名，去数据库取出其对象
		//3.new一个登陆验证员，给登录验证员传三个值：user对象，user的真实密码，当前AuthRealm的名字
		//4.shiro会自动校验

		UsernamePasswordToken loginTonken = (UsernamePasswordToken)token;
		String username = loginTonken.getUsername();
		
		UserExample ue = new UserExample();
		
		Criteria ueCriteria = ue.createCriteria();
		ueCriteria.andUsernameEqualTo(username);
		List<User> users = userService.selectByExample(ue);
		//给验证员传三个值：user对象，user的真实密码，当前AuthRealm的名字
		System.out.println("authrealm:" + username + users.get(0).getPassword());
		AuthenticationInfo info = new SimpleAuthenticationInfo(users.get(0), users.get(0).getPassword(), this.getName());
		return info;
	}

}
